<template>
    <div class="main-layout">
        <div class="_breadcrumb">
            <Breadcrumb :items="breadcrumbItems" />
        </div>

        <main class="content">
            <header class="article-header">
                <h1>{{ article.title }}</h1>
                <div class="meta">
                    <div class="left">
                        <div class="comment"><img src="/icon/detail/user.png" /><span>作者：{{ article.author || 'admin'
                                }}</span></div>
                        <div class="comment"><img src="/icon/detail/time.png" /><span>时间：{{
                            formatDate(article.publishDate) }}</span></div>
                        <div class="comment"><img src="/icon/detail/eye.png" /><span>浏览量：{{ article.views }} 次</span>
                        </div>
                        <div class="comment" v-if="article.channel?.articleModel.code === 'kpzysp'"><img
                                src="/icon/video-detail/download.png" /><span>下载量：{{ article.downloads }} 次</span></div>
                    </div>
                    <div class="right">
                        <div class="download comment" @click="downloadFile"
                            v-if="article.channel?.articleModel.code === 'kpzysp'">
                            <img src="/icon/science/download.png" /><span>下载</span>
                        </div>
                        <div class="comment collect" v-if="currentRoute != 'members'"
                            @click="collectHandle(article.collect, article.id)">
                            <img v-if="!article.collect" src="/icon/detail/star.png" />
                            <img v-else src="/icon/detail/star-active.png" />
                            <span>收藏</span>
                        </div>
                        <!-- <div class="comment share"><img src="/icon/detail/wechat.png" /><span>分享</span></div> -->
                    </div>
                </div>
            </header>

            <slot name="content">

            </slot>
            <!-- 上一篇下一篇 -->

            <footer>
                <div v-if="neighbors" class="article-navigation">
                    <NuxtLink v-if="neighbors.prev"
                        :to="localePath(`/${neighbors.prev.nav}/${neighbors.prev.category}/${neighbors.prev.id}`)"
                        class="nav-link prev">
                        上一篇：<span>{{ neighbors.prev.title }}</span>
                    </NuxtLink>

                    <NuxtLink v-if="neighbors.next"
                        :to="localePath(`/${neighbors.next.nav}/${neighbors.next.category}/${neighbors.next.id}`)"
                        class="nav-link next">
                        下一篇：<span>{{ neighbors.next.title }}</span>
                    </NuxtLink>
                </div>
                <slot name="footer">

                </slot>
            </footer>
        </main>
    </div>
</template>
<script setup>
import { formatDate } from '@/utils/date'

const props = defineProps({
    article: {
        type: Object,
        default: ''
    },
    breadcrumbItems: {
        type: Array,
        default: () => []
    },
    neighbors: {
        type: Object,
        default: () => ({})
    },
    currentRoute: {
        type: String,
        default: ''
    }
})

const { $fetchAuth } = useNuxtApp()
const userStore = useUserStore()
const localePath = useLocalePath()
const router = useRouter()
const route = useRoute()

//下载文件
const downloadFile = async () => {
    // 登录后才能下载
    if (!userStore.user) {
        ElMessageBox.confirm('您需要登录才能下载该文件，是否去登录？', '提示', {
            confirmButtonText: '去登录',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            type: 'warning'
        }).then(() => {
            router.push(localePath('/Login') + `?redirect=${encodeURIComponent(route.fullPath)}`);
        }).catch(() => {
            // 用户取消操作
        });
    } else {
        //先获取下载参数
        const downloadParams = ref(null);
        if (!props.article?.id) {
            showError({ statusCode: 404 })
        } else {
            downloadParams.value = await $fetchAuth(`/app/api/article/download-params/${props.article.id}`, {
                method: 'GET',
            })
        }

        const downloadParamsObj = computed(() => {
            if (downloadParams.value) {
                const params = new URLSearchParams(downloadParams.value.data);
                return Object.fromEntries(params);
            }
            return {};
        });

        const { data } = await $fetchAuth(`/app/api/article/download-file/${props.article.id}`, {
            method: 'GET',
            params: {
                downloadType: 'video',
                ...downloadParamsObj.value
            }
        })

        const link = document.createElement('a');
        link.href = data.fileUrl;
        link.download = data.fileName
        link.click();
        window.URL.revokeObjectURL(link.href)
        // const blob = new Blob([data], { type: 'application/octet-stream' });
        // const url = window.URL.createObjectURL(blob);
        // const link = document.createElement('a');
        // link.href = url;
        // // 获取文件name + 时间戳
        // link.download = `${props.article?.title || 'untitled' + new Date().getTime()}.mp4`;
        // link.click();
        // window.URL.revokeObjectURL(url);
    }
}

const collectHandle = async (iscollect, id) => {
    try {
        if (!userStore.user) {
            router.push(localePath('/Login'));
            return;
        }

        if (iscollect) {
            const { data: cancleCollect } = await $fetchAuth(`/app/api/core/user-collects/${id}`, {
                method: 'DELETE'
            });
            if (cancleCollect.status === 0) {
                props.article.collect = !iscollect;
            }
            return;
        } else {
            const { data: collect } = await $fetchAuth(`/app/api/core/user-collects`, {
                method: 'POST',
                body: { articleId: id }
            });
            if (collect.status === 0) {
                props.article.collect = !iscollect;
            }
            return;
        }
    } catch (error) {
        console.error('操作失败:', error);
    }
}
</script>
<style scoped lang="scss">
@use '@/assets/scss/main' as *;

.main-layout {
    max-width: 1200px;
    margin: 0rem auto;
    padding-bottom: 2rem;

    .content {
        background: white;
        padding: 2rem;
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.75rem rgba(0, 0, 0, 0.1);

        .article-header {
            border-bottom: 1px solid #eee;
            padding-bottom: 1rem;
            margin-bottom: 1rem;

            h1 {
                color: $mytext-color;
                font-size: 1.4rem;
                margin-bottom: 1rem;
                text-align: center;
            }

            .meta {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .left {
                    display: flex;
                    align-items: center;
                    gap: 1rem;

                    .comment {
                        display: flex;
                        align-items: center;
                        gap: .2rem;
                        font-size: 1rem;
                        color: #666;

                        img {
                            width: 1.3rem;
                            height: 1.2rem;
                            border-radius: 50%;
                        }
                    }
                }

                .right {
                    display: flex;
                    align-items: center;
                    gap: 1rem;

                    img {
                        width: 1.3rem;
                        height: 1.3rem;
                    }

                    .comment {
                        display: flex;
                        align-items: center;
                        font-size: 1rem;
                        color: #666666;
                        gap: .2rem;
                        cursor: pointer;

                        &.collect {
                            img {
                                margin-top: -1px;
                            }
                        }
                    }
                }
            }
        }

        footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 2rem;
            border-top: 1px solid #eee;
            padding-top: 2rem;

            .article-navigation {
                .nav-link {
                    color: $myprimary-color;
                    text-decoration: none;
                    display: block;
                    transition: all 0.3s ease-in-out;
                    font-size: 1rem;
                    color: #666;

                    span {
                        color: $myprimary-color;

                        &:hover {
                            text-decoration: underline;
                        }
                    }

                    &:first-child {
                        margin-bottom: .5rem;
                    }
                }
            }
        }
    }
}

@media (max-width: 768px) {
    .main-layout {
        ._breadcrumb {
            padding: 0 .8rem;
        }

        .content {
            padding: .8rem;
            width: 94%;
            margin: 0 auto;

            .article-header {
                h1 {
                    font-size: 1rem;
                }

                .meta {
                    flex-direction: column;
                    align-items: flex-start;
                    gap: 1rem;

                    .left {
                        display: flex;
                        gap: 0.5rem;

                        img {
                            display: none;
                        }
                    }

                    .right {
                        display: flex;
                        gap: 0.5rem;
                    }
                }
            }
        }

        footer {
            flex-direction: column;
            align-items: flex-start;
            gap: 1rem;
        }
    }
}
</style>